#pragma once

#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <pthread.h>
#include <signal.h>
#include <signal.h>
#include "log.hpp"
// #include "ThreadPool.hpp"
// #include "Task.hpp"
// #include "Daemon.hpp"


using namespace std;
uint16_t defaultport = 8080;
string defaultip = "0.0.0.0";
class TcpServe
{
public:
    TcpServe(const uint16_t &port = defaultport, const string &ip = defaultip):listensockfd(-1),port_(port),ip_(ip)
    {
    }
    void Init()//初始化
    {
        listensockfd=socket(char16_t);
        if (listensockfd < 0)
        {
            lg(Fatal, "socket create error, sockfd: %d", listensockfd);
            exit(SOCKET_ERR);
        }
        else
        {
            lg(Info, "socket create success, sockfd: %d", listensokfd);
        }
        int opt = 1;
        setsockopt(listensock_, SOL_SOCKET, SO_REUSEADDR|SO_REUSEPORT, &opt, sizeof(opt)); // 防止偶发性的服务器无法进行立即重启(tcp协议的时候再说)
        //设置端口,IP信息
        struct sockaddr_in local;
        local.sin_family=AF_INET;
        local.sin_port=htons(port_);
        local.sin_addr.s_addr=inet_addr(ip_.c_str());
        //绑定端口信息到套接字
        if (bind(listensock_, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            lg(Fatal, "bind error, errno: %d, errstring: %s", errno, strerror(errno));
            exit(BindError);
        }

        lg(Info, "bind socket success, listensock_: %d", listensock_);

        // Tc  p是面向连接的，服务器一般是比较“被动的”，服务器一直处于一种，一直在等待连接到来的状态,监听
        if (listen(listensock_, backlog) < 0)
        {
            lg(Fatal, "listen error, errno: %d, errstring: %s", errno, strerror(errno));
            exit(ListenError);
        }

        lg(Info, "listen socket success, listensock_: %d", listensock_);
    }
    void start()
    {
        while(true)
        {
            struct sockaddr_in client;
            socklen_t len=sizeof(client);
            int sockfd=accept(listensockfd,&client,&len);
            if (sockfd < 0)
            {
                lg(Warning, "accept error, errno: %d, errstring: %s", errno, strerror(errno)); //?
                continue;
            }
        }
    }
private:
    int listensockfd;
    uint16_t port_;
    string  ip_;
};